package com.hashnode.lb.MyLB;

import com.hashnode.lb.LoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class LoadBalancerImpl implements LoadBalancer {
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncreament(){

        for(;;){
            int current = atomicInteger.get();
            int next = current >= 2147483647 ? 0 : current + 1;
            if(atomicInteger.compareAndSet(current,next)){
                return next;
            }

        }
    }

    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstaces) {
//        int index = atomicInteger.addAndGet(1) % serviceInstaces.size();
        int index = getAndIncreament() % serviceInstaces.size();
        return serviceInstaces.get(index);
    }
}
